package com.zlx.sharelive.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.lzj.pass.dialog.PayPassDialog;
import com.lzj.pass.dialog.PayPassView;
import com.zlx.module_base.base_api.res_data.BaseBean;
import com.zlx.module_base.base_api.res_data.DynamicListBean;
import com.zlx.module_base.base_api.res_data.DynamicOrderBody;
import com.zlx.module_base.base_api.res_data.QueryByBean;
import com.zlx.module_base.base_api.util.ApiUtil;
import com.zlx.module_base.base_fg.BaseFg;
import com.zlx.module_base.base_util.SPUtil;
import com.zlx.module_base.base_util.TimeUtil;
import com.zlx.module_network.api1.livedata.BaseObserver;
import com.zlx.module_network.api1.livedata.BaseObserverCallBack;
import com.zlx.module_network.bean.ApiResponse;
import com.zlx.sharelive.Constants;
import com.zlx.sharelive.R;
import com.zlx.sharelive.activity.CommunityDetailsAc;
import com.zlx.sharelive.adapter.CommonRecyclerViewAdapter;
import com.zlx.sharelive.adapter.CommonRecyclerViewHolder;
import com.zlx.sharelive.utils.GlideImgManager;
import com.zlx.sharelive.utils.StringUt;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 点赞——文章
 */
public class ArticleFg extends BaseFg {

    @BindView(R.id.sw_layout)
    SwipeRefreshLayout sw_layout;
    @BindView(R.id.rv_data)
    RecyclerView rv_data;

    private String over;
    private int videoCount;
    private int page = 1;
    private String isSelf = "", isTj = "", city = "", izFee = "";
    private List<DynamicListBean.InfoDTO> mList = new ArrayList<>();
    private CommonRecyclerViewAdapter<DynamicListBean.InfoDTO> mAdapter;
    private List<String> mImageList = new ArrayList<>();
    private CommonRecyclerViewAdapter<String> mImageAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.fg_article;
    }

    @Override
    protected void initViews() {
        super.initViews();

        initRecyclerView();
        getDynamicList();
        queryById();

        sw_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getDynamicList();
            }
        });
    }

    /**
     * 根据用户id查询个人信息
     */
    private void queryById() {
        ApiUtil.getLoginApi().queryById(SPUtil.getToken(getContext()), (String) SPUtil.get(getContext(), Constants.SP_ID, ""))
                .observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<QueryByBean>>() {
                    @Override
                    public void onSuccess(ApiResponse<QueryByBean> data) {
                        if (null != data) {
                            if (null != data.getData()) {
                                if (null != data.getData().getInfo()) {
                                    if (data.getData().getInfo().size() > 0) {
                                        if (null != data.getData().getInfo().get(0).getResult()) {
                                            if (!StringUt.isEmpty(data.getData().getInfo().get(0).getResult().getVideoCount())) {
                                                videoCount = Integer.valueOf(data.getData().getInfo().get(0).getResult().getVideoCount());
                                                if (!StringUt.isEmpty(data.getData().getInfo().get(0).getResult().getMoney())) {
                                                    over = data.getData().getInfo().get(0).getResult().getMoney();
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();

                    }
                }));
    }


    private void getDynamicList() {
        ApiUtil.getServiceApi().getDynamicList(SPUtil.getToken(getContext()),
                isSelf,
                "0",
                city,
                izFee,
                "",
                String.valueOf(page),
                "",
                "",
                isTj,
                "1",
                "").observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<DynamicListBean>>() {
            @Override
            public void onSuccess(ApiResponse<DynamicListBean> data) {
                sw_layout.setRefreshing(false);
                mList.clear();
                if (null != data) {
                    if (null != data.getData()) {
                        mList.addAll(data.getData().getInfo());
                    }
                }
                mAdapter.notifyDataSetChanged();
            }
        }));
    }


    /**
     * 初始化列表
     */
    private void initRecyclerView() {
        rv_data.setLayoutManager(new LinearLayoutManager(getContext()));

        mAdapter = new CommonRecyclerViewAdapter<DynamicListBean.InfoDTO>(getContext(), mList) {
            @Override
            public void convert(CommonRecyclerViewHolder holder, DynamicListBean.InfoDTO entity, int position) {
                ImageView iv_community_head = holder.getView(R.id.iv_community_head);

                GlideImgManager.glideLoader(getContext(), entity.getAvatar(), iv_community_head, 0);

                holder.setText(R.id.tv_community_nickname, entity.getNickname());

                ImageView iv_community_vip = holder.getView(R.id.iv_community_vip);
                ImageView iv_community_goddess = holder.getView(R.id.iv_community_goddess);

                holder.setText(R.id.tv_reward_number, entity.getReword());

                if (entity.getIsDz().equals("1")) {
                    ((ImageView) holder.getView(R.id.iv_fabulous_img)).setImageResource(R.mipmap.fabulous_img_true);
                } else {
                    ((ImageView) holder.getView(R.id.iv_fabulous_img)).setImageResource(R.mipmap.fabulous_img2);
                }

                try {
                    holder.setText(R.id.tv_time, TimeUtil.getTimeStringAutoShort2(TimeUtil.ConverToDate(entity.getDatetime()), true));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                holder.setText(R.id.tv_community_address, entity.getCity());
                holder.setText(R.id.tv_community_text_title, entity.getTitle());
                holder.setText(R.id.tv_community_text_content, entity.getText());
                holder.setText(R.id.tv_share_number, entity.getShares());
                holder.setText(R.id.tv_fabulous_number, entity.getLikes());
                holder.setText(R.id.tv_comment_number, entity.getComments());

                holder.setText(R.id.tv_community_time, entity.getDatetime());

                mImageList.clear();
                if (!StringUt.isEmpty(entity.getThumbs())) {
                    mImageList.add(entity.getThumbs());
                }
                if (!StringUt.isEmpty(entity.getThumb2())) {
                    mImageList.add(entity.getThumb2());
                }
                if (!StringUt.isEmpty(entity.getThumb3())) {
                    mImageList.add(entity.getThumb3());
                }
                if (!StringUt.isEmpty(entity.getThumb4())) {
                    mImageList.add(entity.getThumb4());
                }
                if (!StringUt.isEmpty(entity.getThumb5())) {
                    mImageList.add(entity.getThumb5());
                }
                if (!StringUt.isEmpty(entity.getThumb6())) {
                    mImageList.add(entity.getThumb6());
                }
                if (!StringUt.isEmpty(entity.getThumb7())) {
                    mImageList.add(entity.getThumb7());
                }
                if (!StringUt.isEmpty(entity.getThumb8())) {
                    mImageList.add(entity.getThumb8());
                }
                if (!StringUt.isEmpty(entity.getThumb9())) {
                    mImageList.add(entity.getThumb9());
                }

                RecyclerView rv_community_image = holder.getView(R.id.rv_community_image);

                rv_community_image.setLayoutManager(new GridLayoutManager(getContext(), 4));

                mImageAdapter = new CommonRecyclerViewAdapter<String>(getContext(), mImageList) {
                    @Override
                    public void convert(CommonRecyclerViewHolder holder, String entity, int position) {
                        ImageView iv_community_image = holder.getView(R.id.iv_community_image);

                        GlideImgManager.glideLoader(getContext(), entity, iv_community_image, 1);
                    }

                    @Override
                    public int getLayoutViewId(int viewType) {
                        return R.layout.item_community_image_layout;
                    }
                };
                rv_community_image.setAdapter(mImageAdapter);
            }


            @Override
            public int getLayoutViewId(int viewType) {
                return R.layout.item_community_type2;
            }
        };

        rv_data.setAdapter(mAdapter);

        mAdapter.setOnRecyclerViewItemClickListener(new CommonRecyclerViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                if (mList.get(position).getIzFee().equals("0")) {
                    startActivity(new Intent(getContext(), CommunityDetailsAc.class)
                            .putExtra("id", mList.get(position).getId()));
                } else {
                    //收费
                    dialogPay(
                            mList.get(position).getId(),
                            mList.get(position).getMoney());
                }
            }
        });
    }

    /**
     * 购买
     */
    private void dialogPay(String id, String money) {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(getContext(), R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(getContext(), R.layout.dialog_play_video, null);
        dialog.setContentView(view);

        TextView tv_money = view.findViewById(R.id.tv_money);
        tv_money.setText("￥" + money);

        TextView tv_over = view.findViewById(R.id.tv_over);

        ImageView iv_close = view.findViewById(R.id.iv_close);

        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        if (StringUt.isEmpty(over)) {
            tv_over.setText("￥0");
        } else {
            tv_over.setText("￥" + over);
        }

        TextView bt_play = view.findViewById(R.id.bt_play);

        bt_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!StringUt.isEmpty(money) && !StringUt.isEmpty(over)) {
                    if (Double.valueOf(over) > Double.valueOf(money)) {
                        //钱够支付
                        purchaseVideo(id, money);
                        dialog.dismiss();
                    } else {
                        Toast.makeText(getContext(), "余额不足", Toast.LENGTH_SHORT).show();
                    }
                } else if (StringUt.isEmpty(over)) {
                    Toast.makeText(getContext(), "余额不足", Toast.LENGTH_SHORT).show();
                }
            }
        });

        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        //设置弹出动画
//        window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

    }

    /**
     * 余额购买视频
     *
     * @param id
     * @param money
     */
    private void purchaseVideo(String id, String money) {
        dialogPass(id, money);
    }

    /**
     * 支付密码
     */
    private void dialogPass(String id, String money) {
        DynamicOrderBody dynamicOrderBody = new DynamicOrderBody();
        dynamicOrderBody.setDynamicId(id);
//        dynamicOrderBody.setMoney(money);

        final PayPassDialog dialog = new PayPassDialog(getContext());
        dialog.getPayViewPass()
                .setRandomNumber(true)
                .setPayClickListener(new PayPassView.OnPayClickListener() {
                    @Override
                    public void onPassFinish(String passContent) {
                        //6位输入完成回调
                        Log.d("ret", "joker  输入的密码===" + passContent);
                        dynamicOrderBody.setWalletPassword(passContent);
                        ApiUtil.getVideoApi().dynamicOrder(SPUtil.getToken(getContext()),
                                dynamicOrderBody).observe(getViewLifecycleOwner(), new BaseObserver<>(new BaseObserverCallBack<ApiResponse<BaseBean>>() {
                            @Override
                            public void onSuccess(ApiResponse<BaseBean> data) {
                                if (data.getData().getCode() == 0) {
                                    Toast.makeText(getContext(), "购买成功", Toast.LENGTH_SHORT).show();
                                    dialog.dismiss();
                                    page = 1;
                                    getDynamicList();
                                    queryById();
                                }
                            }
                        }));
                    }

                    @Override
                    public void onPayClose() {
                        dialog.dismiss();
                        //关闭弹框
                    }

                    @Override
                    public void onPayForget() {
                        dialog.dismiss();
                        //点击忘记密码回调
                    }
                });

    }

}
